package org.hcf.api.tencent.callback;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hcf.api.base.Const;
import org.hcf.api.base.Helper;
import org.hcf.api.tencent.callback.info.group.GroupMemberJoinInfo;
import org.hcf.api.tencent.callback.info.group.base.MemberInfo;
import org.hcf.api.intf.ICallBack;
import org.hcf.data.RedisUtils;
import org.hcf.data.entity.ChatGroup;
import org.hcf.data.entity.ChatGroupInfo;

import java.util.Set;

@Slf4j
@Data
/** 群成员加入回调 */
public class CallbackGroupMemberJoinHandler implements ICallBack {
    @Override
    public String getCommand() {
        return Const.CMD.GROUP_MEMBER_JOIN_AFTER;// "Group.CallbackAfterNewMemberJoin";
    }

    @Override
    public JSONObject action(JSONObject data) {
        log.info("收到群成员加入回调:" + data);
        GroupMemberJoinInfo info = data.toJavaObject(GroupMemberJoinInfo.class);
        log.info("反序列化入群信息:" + JSONObject.toJSON(info));

        if (!getCommand().equals(info.getCallbackCommand())) {
            log.error("入群消息中[" + data.getString("CallbackCommand") + "]命令不匹配");
            return Helper.toSuccess();
        }
        ChatGroup group = RedisUtils.getGroupByAccount(info.getGroupId());

        if (group != null) {
            Set<Long> uids = Helper.getPluginUserIds();
            for (MemberInfo member : info.getNewMemberList()) {
                if (member != null && NumberUtil.isNumber(member.getMember_Account())) {
                    long userId = Long.parseLong(member.getMember_Account());
                    ChatGroupInfo memberInfo = CallbackGroupCreateHandler.addGroupMember(userId, info.getGroupId(), null);
                    if (uids.contains(userId)) {
                        RedisUtils.initGA2UID(info.getGroupId(), userId);
                        if (memberInfo != null) RedisUtils.initUID2GMID(userId, memberInfo.getInfoId());
                    }
                }
            }
        } else log.error("群不存在！！！无法回调消息:" + data);
        return Helper.toSuccess();
    }
}
